# -*- coding: utf-8 -*-

from program_top.utilities.environment_and_platform import environment_initialisation
from program_top.utilities.csv_and_json_serialisation import clean_load_json
from program_top.utilities.debugging import callback_debug_start


from ctpGateway.ctpGateway import CtpGateway,CtpTdApi
from vtGateway import VtLogData
import json,time

class auto_td(CtpTdApi):
	'''结算完成后通知策略的'''
	
	
	pass

class auto_gateway(CtpGateway):
	'''霸帝用的自动连接的ctp接口，完成账户资金、持仓、订单各方面查询后，通知策略执行初始化'''
	
	def connect(self):
		"""连接"""
		# 载入json文件
		
		fileName=self._environment_pack['instance_path']['config_file_dir']+'config.json'
		
		try:
			f=file(fileName)
		except IOError:
			log=VtLogData()
			log.gatewayName=self.gatewayName
			log.logContent=u'读取连接配置出错，请检查'
			self.onLog(log)
			return
		
		# 解析json文件
		setting=json.load(f)
		try:
			userID=str(setting['userID'])
			password=str(setting['password'])
			brokerID=str(setting['brokerID'])
			tdAddress=str(setting['tdAddress'])
			mdAddress=str(setting['mdAddress'])
		except KeyError:
			log=VtLogData()
			log.gatewayName=self.gatewayName
			log.logContent=u'连接配置缺少字段，请检查'
			self.onLog(log)
			return
		
		# 创建行情和交易接口对象
		self.mdApi.connect(userID, password, brokerID, mdAddress)
		self.tdApi.connect(userID, password, brokerID, tdAddress)
		
		# 初始化并启动查询
		self.initQuery()
		pass
	
	def __init__(self, eventEngine, gatewayName='auto_gateway'):
		super(auto_gateway, self).__init__(eventEngine,gatewayName)#调用ctp的构造函数
		environment_initialisation(self)
		config_filename=self._environment_pack['instance_path']['config_file_dir']+'config.json'
		
		self._business_config=clean_load_json(config_filename)
		
		if self._business_config['auto_connect']:#如果要自动加载
			self.tdApi=None#清除掉原来的td
			self.tdApi=auto_td(self)#用自己的td替代
			#self.connect()
			pass
		pass
	
	def ui_register(self,ui_main_ref):
		'''传入并保存ui界面的引用地址，由UI构造完毕后主动调用'''
		self.__auto_ui=ui_main_ref
		self.connect()
		pass
	
	pass